import java.io.*;
import java.text.*;

public class Decrypter {
	private static final int row = 50;
	private static final int column = 80;
	private static final String currentDirectory = System.getProperty("user.dir") + "/";
	private static final String cipherTextDirectory = currentDirectory + "cipherText/";
	private static final String decryptedTextDirectory = currentDirectory + "plainTextOutput/";
	private static final String padDirectory = currentDirectory + "padFilesGenerated/";
	private String[] cipherTexts;
	private String[] padFiles;
	private byte[] c;
	private byte[] p;
	private byte[] d;
	
	public Decrypter(String cipherTextList) {
		cipherTexts = cipherTextList.split(",");
        // NOTE: had to change the input b/c of presence of .svn directory
        String[] padFilesTemp;
		padFilesTemp = new File(padDirectory).list();
        this.padFiles = new String[padFilesTemp.length - 1];
        for(int i = 0; i < padFilesTemp.length - 1; i++) {
            padFiles[i] = padFilesTemp[i + 1];
        }
	}
	
	public void decrypt() {
		try {
			checkDirectory(decryptedTextDirectory);
			NumberFormat nf = new DecimalFormat("0");
			for (int i = 0; i < cipherTexts.length; i++) {
//			for(String cipherText : cipherTextList.split(",")) {
				c = readFile(cipherTextDirectory + "c" + cipherTexts[i] + ".txt");
				p = readFile(padDirectory + padFiles[i%padFiles.length]);
			    d = new byte[row * column];
				for (int j = 0; j < (row * column); j++) {
					byte value = (byte)(((c[j]-32)-(p[j]-32))%95);
					if (value < 0) { value += 95; }
					d[j] = (byte)(value + 32);
				}
				writeFile(decryptedTextDirectory + "d" + nf.format(i+1), d);
			}
		} catch (Exception e) { System.err.println("ERROR: " + e); }
	}
	
	//getters and setters for CryptAnalyzer-------
	public byte[] getD(){
		return d;
	}
	public void setFirstCiphertext(String c){
		cipherTexts[0] = c;
	}
	public void setFirstPadFiles(String p){
		padFiles[0] = p;
	}
	//---------------------------------
	
	private void checkDirectory(String directory) {
		File d = new File(directory);
		if (!d.exists()) { d.mkdir(); }
		String[] f = d.list();
		for (int i = 0; i < f.length; i++) { new File(d, f[i]).delete(); }
	}
	
	private byte[] readFile(String fileName) throws Exception {
		byte[] retVal = new byte[row * column];
			FileInputStream fis = new FileInputStream(fileName);
			fis.read(retVal);
			fis.close();
		return retVal;
	}
	
	private void writeFile(String fileName, byte[] b) throws Exception {
			FileOutputStream fos = new FileOutputStream(fileName + ".txt");
			fos.write(b);
			fos.close();
	}
}
